//file模块
const fs = require("fs");
//http模块
const http = require("http");
//path模块(获取文件的后缀名)
const path = require("path");
//url
const url = require("url");
//获取自己定的模块
const mimeModel = require("./model/mime.js");
//文件目录
const staticFolder = "static/";


http.createServer(function (request, response) {
    //获取请求的uri(去掉参数)
    let pathName = url.parse(request.url).pathname;
    //设置默认的请求值
    if (pathName == "/") {
        pathName = "/index.html"
    }
    //过滤请求
    if (pathName != "/favicon.ico") {
        console.log(pathName);
        //获取
        fs.readFile(staticFolder + pathName, function (error, result) {
            if (error) {
                console.log("404");
                fs.readFile(staticFolder + "404.html", function (error, data404) {
                    response.writeHead(404, mimeModel.getMime(path.extname("404.html")));
                    response.write(data404);
                    response.end();
                });
            } else {
                //向页面返回数据
                let mimeType = mimeModel.getMime(path.extname(pathName));
                let head = "Content-Type :" + mimeType;
                response.writeHead(200, head);
                response.write(result);
                response.end();
            }
        });
    }
}).listen(8080);

console.log("server init with port:8080");